# -*- coding: utf-8 -*-

"""
controller base for user
"""

import tornado.web
from framework.controller import Controller
from framework.session import Session
import hashlib
import base64
import uuid

class UserController(Controller):
    """user base controller"""

    _user = dict()

    def __init__(self, application, request, **kwargs):
        """call tornado.web"""
        super(UserController, self).__init__(application, request, **kwargs)

    # Entry points
    def initialize(self):
        """admin login"""
        if self.current_user:
            if not self.current_user.get('id'):
                err = dict(err=1, msg=u'无权限访问')
                self.ajax_out(**err)
                return False
        return True

    @tornado.web.authenticated
    def get(self):
        """default get"""
        self.write_error(404)

    @tornado.web.authenticated
    def post(self):
        """default post"""
        self.write_error(404)

    def get_current_user(self):
        """user login auth handler"""
        thor = self.get_secure_cookie('userthor')
        if not thor:
            thor = base64.b64encode(uuid.uuid4().bytes + uuid.uuid4().bytes)
            self.set_secure_cookie('userthor', thor)
        sess = Session(thor)
        # session save logined
        user = sess.get_all()
        if user:
            return user
        nick = self.get_secure_cookie('usernick')
        token = self.get_secure_cookie('usertoken')
        user_id = self.get_secure_cookie('userid')
        salt = self.request.remote_ip + self.request.headers['User-Agent']
        if (not nick) or (not token) or (not salt) or (not user_id):
            return
        # check
        md5 = hashlib.md5()
        # pass_str = '%s_%s_%s' % (nick, user_id, salt)
        md5.update('%s_%s_%s' % (nick, user_id, salt))
        # pw = md5.hexdigest()
        if token != md5.hexdigest():
            return
        self._user = dict(id=user_id, name=nick, type=0, token=token)
        sess.set_hmset(self._user)
        return self._user

    def render(self, template_name, **kwargs):
        """
        join user
        :param template_name: 
        :param kwargs: 
        :return: 
        """
        user = dict()
        if self.current_user:
            user['user'] = self.current_user
        kwargs.update(user)
        super(UserController, self).render(template_name, **kwargs)
